<template>
<div>
  <el-tooltip :open-delay="1000"
              placement="top"
              v-if="getFilterLabel&&getFilterLabel.length>30">
    <div slot="content">{{getFilterLabel}}</div>
    <el-select v-model="optionsId"
               :placeholder="$t('custom.component.gadget.ticketsFilter')"
               popper-class="nextticketFilter"
               ref="referenceselect"
               style="width:285px; white-space: nowrap;text-overflow: ellipsis;overflow: hidden;"
               clearable
               @clear="clearFilter"
               @change="changeFilterName">
      <el-option :value="optionsId"
                 v-if="$hasPermission('sys:nextticket:filter')">
        <div @click="openFilterDialog"  v-if="$route.path!=='/nextTicket'"
             style="margin:4px auto 10px;width:285px;height:28px;color:#17B3A3;background-color: rgba(19, 141, 199, 0.1);border:1px dashed #17B3A3;border-radius:4px;text-algin:center;line-height:28px">
          <div class="add_new_filter"
               style="display:flex;justify-content:center">
            <i class="cuifont icon_add_square" 
               style="color:#17B3A3;font-size:14px;font-weight:400"> {{$t('custom.component.gadget.addFilter')}}</i>
          </div>
        </div>
      </el-option>
      <el-option v-for="(item,index) in options"
                 :key="item.id"
                 :label="item.label"
                 :value="item.id">
        <div style="display: flex;justify-content:space-between;">
        <ZTooltip :content="item.label"
                           :line="1"
                          placement="top">
                          <span style="flex:1">{{ item.label }}</span>
        </ZTooltip>
        <div  v-if="$route.path!=='/nextTicket'">
            <el-button v-if="$hasPermission('sys:nextticket:filter')"
                     style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                     size='mini'
                     type="text"
                     @click.stop='delNextTicketFilter(item)'>
            <i class="cuifont icon_delete"
               style="font-size:14px;color:#CCC"></i>
          </el-button>
          <el-tooltip v-if="$hasPermission('sys:nextticket:filter')"
                      :open-delay="1000"
                      class="item"
                      effect="dark"
                      content="Copy"
                      placement="top">
            <el-button style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                       size='mini'
                       type="text"
                       @click.stop='copyNextTicketFilter(item)'>
              <i class="cuifont icon_copy"
                 style="font-size:14px;color:#CCC"></i>
            </el-button>
          </el-tooltip>
          <el-button v-if="$hasPermission('sys:nextticket:filter')"
                     style="float: right;font-size: 14px;margin-top: 3px;"
                     size='mini'
                     type="text"
                     @click.stop='editFilterDialog(index, item)'>
            <i class="cuifont icon_edit"
               style="font-size:14px;color:#CCC"></i>
          </el-button>
        </div>
        </div>
     
      </el-option>

    </el-select>
  </el-tooltip>
  <el-tooltip :open-delay="1000" placement="top" v-else >
    <div slot="content">{{$t('custom.component.gadget.filterText')}}</div>
    <el-select v-model="optionsId"
               :placeholder="$t('custom.component.gadget.ticketsFilter')"
               ref="referenceselect"
               popper-class="nextTicket_filterText"
               style="width:285px; white-space: nowrap;text-overflow: ellipsis;overflow: hidden;"
               clearable
               @change="changeFilterName"
               @clear="clearFilter">
      <el-option :value="optionsId" v-if="$hasPermission('sys:nextticket:filter')&&$route.path!=='/nextTicket'">
        <div @click="openFilterDialog"
             style="margin:4px auto 10px;width:285px;height:28px;color:#17B3A3;background-color: rgba(19, 141, 199, 0.1);border:1px dashed #17B3A3;border-radius:4px;text-algin:center;line-height:28px">
          <div class="add_new_filter" v-if="$route.path!=='/nextTicket'"
               style="display:flex;justify-content:center">
            <i class="cuifont icon_add_square" 
               style="color:#17B3A3;font-size:14px;font-weight:400"> {{$t('custom.component.gadget.addFilter')}}</i>
          </div>
        </div>
      </el-option>
      <el-option v-for="(item,index) in options"
                 :key="item.id"
                 :label="item.label"
                 :value="item.id">
                        <div style="display: flex;justify-content:space-between;">
                          <ZTooltip :content="item.label"
                           :line="1"
                          placement="top">
                          <span style="flex:1">{{ item.label }}</span>
                          </ZTooltip>
                        
                          <span  v-if="$route.path!=='/nextTicket'">
                              <el-button v-if="$hasPermission('sys:nextticket:filter')"
                                       style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                       size='mini'
                                       type="text"
                                       @click.stop='delNextTicketFilter(item)'>
                              <i class="cuifont icon_delete"
                                 style="font-size:14px;color:#CCC"></i>
                            </el-button>
                            <el-tooltip v-if="$hasPermission('sys:nextticket:filter')"
                                        :open-delay="1000"
                                        class="item"
                                        effect="dark"
                                        content="Copy"
                                        placement="top">
                              <el-button style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                         size='mini'
                                         type="text"
                                         @click.stop='copyNextTicketFilter(item)'>
                                <i class="cuifont icon_copy"
                                   style="font-size:14px;color:#CCC"></i>
                              </el-button>
                            </el-tooltip>
                            <el-button v-if="$hasPermission('sys:nextticket:filter')"
                                       style="float: right;font-size: 14px;margin-top: 3px;"
                                       size='mini'
                                       type="text"
                                       @click.stop='editFilterDialog(index, item)'>
                              <i class="cuifont icon_edit"
                                style="font-size:14px;color:#CCC"></i>
                            </el-button>
                            </span>
                          </div>
      </el-option>

    </el-select>
  </el-tooltip>

  <el-dialog
      append-to-body
      width="69rem"
      :title="$t('custom.component.columns.filterSettings')"
      :visible.sync="dialogVisible"
      :close-on-click-modal="true"
      @close="handleClose">
    <div>
      <div style="margin-bottom:10px;">
        <span>{{$t('custom.component.gadget.filterName')}}</span>
        <el-input v-model="filterName" placeholder="please enter a filter name" style="width: 26rem;margin-left: 10px;"></el-input>
      </div>
      <type-filter :dataForm='filterSetting.dataForm' v-if="dialogVisible"
                  :nextTicketType='nextTicketType'
                  :scriptItem='filterSetting.scriptItem'
                  ref="typeFilter"
                  :customFieldList="customFieldList"
                  :gadgetSetting="gadgetSetting"
                  @preViewFilter="preViewFilterBack"></type-filter>
    </div>
    <span slot="footer"
          class="dialog-footer"
          style="display: flex;align-items: center;justify-content: space-between;">
        <div>
          <span v-if="filterSetting.lastModifiedBy&&filterSetting.lastModified">
            Last Modified By {{filterSetting.lastModifiedBy}} at {{filterSetting.lastModified|ClientFormat}}</span>
        </div>
        <div>
          <el-button size="small" @click="handleClose">{{$t('cancel')}}</el-button>
          <el-button size="small" @click="handlePreview">{{$t('preview')}}</el-button>
          <el-button type="primary" size="small" :disabled="!$hasPermission('sys:settings:save')" @click="saveFilters">{{$t('save')}}</el-button>
        </div>
      </span>
  </el-dialog>
  <filterPreviewDialog ref="filterPreviewDialog"
                       :modelId="currentTemplateId"
                       :maxRecords="gadgetSetting.maxRecords"
                       :optionsId="optionsId"
                       :gadgetSetting="gadgetSetting"
                       :searchIdentifier="searchIdentifier"
                       :nextTicketType="nextTicketType"
                       :nextTicketAllInfo="nextTicketAllInfo"></filterPreviewDialog>
</div>
</template>

<script>
import { filterJson } from '@/components/next-ticket-filter/filter-json'
// import config from '@/utils/config'
import typeFilter from '@/components/next-ticket-filter'
import filterPreviewDialog from '../filterPreviewDialog'
import ZTooltip from '@/components/storybook/z-tooltip'

export default {
  name: 'search-filter',
  props: ['nextTicketType', 'id', 'gadgetSetting', 'searchIdentifier', 'optionsId','currentTemplateId'],
  components: {
    typeFilter,
    filterPreviewDialog,
    ZTooltip
  },
  data () {
    return {
      isSave: true,
      // optionsId: null,
      options: [],
      filterName: '',
      filterIndex: -1,
      dialogVisible: false,
      filterSetting: {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      },
      nextTicketAllInfo: null,
      customFieldList: []
    }
  },
  computed: {
    getFilterLabel () {
      let name = this.options.find(e => e.id === this.optionsId)
      if (name) return name.name
      else return ''
    }
  },
  methods: {
    getNextTicketCustomField () {
      this.$interface.nextTicket.getNextTicketCustomField().then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let mapping = {
          TextConditions: 'text',
          DateConditions: 'date',
          BooleanConditions: 'boolean',
          NumberConditions: 'number'
        }
        this.customFieldList = res.data
        res.data.forEach(item => {
          if(!this.gadgetSetting.keyArray.some(i=>i.label === item.name))
          this.gadgetSetting.keyArray.push({
            label:item.name,
            type:mapping[item.type],
            value:item.name,
            isCustomField: true
          })
        });
        this.queryFilterOptions()
      })
    },
    queryFilterOptions (getData) {
      let params = {
        gadgetId: this.id,
        type: this.nextTicketType
      }
      this.$interface.nextTicket.getNextTicketOptionsByUser(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data && res.data.map(item => {
          return { label: item.name, value: item.filterJson, ...item }
        })
        if (res.data && res.data.length > 0) {
          this.getLocalFilters(res.data)
        } else {
          if(this.$route.path!=='/nextTicket') {
            this.initFilterDialog()
          }
        }
        if (getData) {
          if (this.optionsId && this.searchIdentifier) {
            this.$emit('getDataList')
          }
        }
      })
    },
    getLocalFilters (data) {
      let filter = data.find(e => e.checked)
      if (filter) {
        this.optionsId = filter.id
      } else {
        if (this.options.length > 0) this.optionsId = this.options[0].id
      }
      this.changeFilterName(this.optionsId)
    },
    initFilterDialog () {
      this.filterName = 'Reactive Service Open Tickets'
      switch (this.nextTicketType) {
        case 'autotask':
          this.filterSetting.dataForm = filterJson.defaultFilterAutoTask
          break
        case 'nextTicket':
          this.filterSetting.dataForm = filterJson.defaultFilterCw
          break
        default:
      }
      this.getKeyList(this.gadgetSetting)
      this.dialogVisible = true
    },
    openFilterDialog () {
      switch (this.nextTicketType) {
        case 'autotask':
          this.filterSetting.dataForm = this._.cloneDeep(filterJson.AutoTaskNewFilterDefault)
          break
        case 'nextTicket':
          this.filterSetting.dataForm = this._.cloneDeep(filterJson.CwNewFilterDefault)
          break
        default:
      }
      this.filterName = ''
      this.getKeyList(this.gadgetSetting)
      this.dialogVisible = true
    },
    getKeyList (data) {
      if (data) {
        this.filterSetting.scriptItem.keyArray = data.keyArray
      }
    },
    delNextTicketFilter (item) {
      const _self = this
      if (!item) return false
      this.$confirm('Are you sure to delete?')
        .then(async () => {
          const params = {
            id: item.id,
            gadgetId: _self.id,
            type: this.nextTicketType
          }
          const { data: res } = await this.$interface.nextTicket.delNextTicketFilter(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            if (this.optionsId === item.id) {
              this.optionsId = null
            }
            this.queryFilterOptions()
            this.$message.success(res.msg)
          }
        })
    },
    async getJiraFilterFields () {
      const { data: res } = await this.$interface.nextTicket.getJiraFilterFields()
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if(res.data) {
        this.$set(this.gadgetSetting,'keyArray',res.data.map(item=>{
          return {
            label:item.name,
            value:item.key,
            ...item
          }
        }))
        this.queryFilterOptions()
      }
    },
    copyNextTicketFilter (item) {
      const params = {
        gadgetId: item.gadgetId,
        name: item.name + ' ' + 'Copy',
        filterStr: item.filterStr,
        filterDatasetStr: item.filterDatasetStr,
        filterJson: item.filterJson,
        type: item.type
      }
      if(item.customFieldFilterStr) {
        params.customFieldFilterStr = item.customFieldFilterStr
      }
      this.$interface.nextTicket.saveNextTicketFilter(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          this.$message.success(res.msg)
          this.queryFilterOptions(true)
        }
      })
    },
    editFilterDialog (index, item) {
      this.filterIndex = index
      this.filterName = item.label
      this.filterSetting.dataForm[this.filterSetting.scriptItem.text] = this._.cloneDeep(item.value)
      if (item.updateDate && item.updaterName) {
        this.filterSetting.lastModifiedBy = item.updaterName
        this.filterSetting.lastModified = item.updateDate
      } else {
        this.filterSetting.lastModifiedBy = item.creatorName
        this.filterSetting.lastModified = item.createDate
      }
      this.getKeyList(this.gadgetSetting)
      this.dialogVisible = true
    },
    clearFilter () {

    },
    changeFilterName (val) {
      let optionItem = this.options.find(e => e.id === this.optionsId)
      this.$emit('changeFilter', { val, optionItem })
    },
    handleClose (done) {
      this.filterIndex = -1
      this.filterName = ''
      this.filterSetting = {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      }
      this.dialogVisible = false
      // this.isSave = false
    },
    async preViewFilterBack (val) {
      try {
        if(this.nextTicketType === 'nextTicket') {
          val[this.filterSetting.scriptItem.text].rules.forEach(item=>{
            if(!item.rules) {
              if(this.customFieldList.some(i=>i.name === item.key)) {
                item.isCustomField = true
              }
            }
          })
        }
        
      } catch (error) {
        
      }
      const { buildFilterStr } = this.$interface.nextTicket
      const { data } = await buildFilterStr({ type: this.nextTicketType, filterJson: val[this.filterSetting.scriptItem.text], maxRecords: Number(this.gadgetSetting.maxRecords) ? Number(this.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords })
      if(data.code === 500&&this.nextTicketType  === 'nextTicket') {
          return this.$message.error(data.msg)
        }
      this.$refs.filterPreviewDialog.ticketDialogVisible = true
      this.$refs.filterPreviewDialog.filterStr = this.nextTicketType.includes('dataset') ? data.data.filterDatasetStr : data.data.filterStr
      this.$refs.filterPreviewDialog.customFieldFilterStr = this.nextTicketType.includes('dataset') ? data.data.filterDatasetStr : data.data.customFieldFilterStr
      this.$refs.filterPreviewDialog.optionItem = val
    },
    async updateData (val) {
      try {
        if(this.nextTicketType === 'nextTicket') {
          val[this.filterSetting.scriptItem.text].rules.forEach(item=>{
            if(!item.rules) {
              if(this.customFieldList.some(i=>i.name === item.key)) {
                item.isCustomField = true
              }
            }
          })
        }
        
      } catch (error) {
        
      }
      if (this.isSave) {
        try {
          let filterStr = ''
        let customFieldFilterStr = ''
        const { buildFilterStr } = this.$interface.nextTicket
        const { data } = await buildFilterStr({ type: this.nextTicketType, filterJson: val[this.filterSetting.scriptItem.text], maxRecords: Number(this.gadgetSetting.maxRecords) ? Number(this.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords })
        if(data.code === 500&&this.nextTicketType  === 'nextTicket') {
          return this.$message.error(data.msg)
        }
        this.dialogVisible = false
        filterStr = data.data.filterStr
        customFieldFilterStr = data.data.customFieldFilterStr
        if (this.filterIndex !== -1) {
          const params = {
            type: this.nextTicketType,
            gadgetId: this.id,
            id: this.options[this.filterIndex].id,
            name: this.filterName,
            filterStr: JSON.stringify({
              filter: filterStr,
              maxRecords: Number(this.gadgetSetting.maxRecords) ? Number(this.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords
            }),
            filterDatasetStr: JSON.stringify({
              filter: data.data.filterDatasetStr,
              maxRecords: Number(this.gadgetSetting.maxRecords) ? Number(this.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords
            }),
            filterJson: val[this.filterSetting.scriptItem.text]
          }
          if (this.nextTicketType.replace('dataset','')  === 'nextTicket') {
            params.filterStr = filterStr
          }
          if (this.nextTicketType  === 'nextTicket') {
            params.customFieldFilterStr = customFieldFilterStr
          }
          const { data: res } = await this.$interface.nextTicket.updateNextTicketFilter(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
            this.queryFilterOptions(true)
          }
        } else {
          const params = {
            type: this.nextTicketType,
            gadgetId: this.id,
            name: this.filterName,
            filterStr: JSON.stringify({
              filter: filterStr,
              maxRecords: Number(this.gadgetSetting.maxRecords) ? Number(this.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords
            }),
            filterJson: val[this.filterSetting.scriptItem.text]
          }
          if (this.nextTicketType.replace('dataset','')  === 'nextTicket') {
            params.filterStr = filterStr
          }
          if (this.nextTicketType  === 'nextTicket') {
            params.customFieldFilterStr = customFieldFilterStr
          }
          const { data: res } = await this.$interface.nextTicket.saveNextTicketFilter(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
            this.queryFilterOptions(true)
          }
        }
        this.filterIndex = -1
        } catch (error) {
        }
      }
    },
    handlePreview () {
      this.$root.eventBus.$emit('filterPreviewDialogUpdateFilter')
    },
    saveFilters () {
      if (this.filterName.trim().length === 0 && this.filterName.match(/^[ ]*$/)) {
        this.$message.error('FilterName Is required.')
        return false
      }
      if (this.$refs.typeFilter.checkdataArr()) {
        // this.dialogVisible = false
        this.updateData(this.$refs.typeFilter.getDataSource())
        this.isSave = true
      }
    },
  },
  destroyed () {
  },
  created () {
    
    if(this.nextTicketType === 'nextTicket') {
      this.getNextTicketCustomField()
    }else if(this.nextTicketType === 'jira'){
      this.getJiraFilterFields()
    }else {

      this.queryFilterOptions()
    }
  }
}
</script>

<style scoped>
.add_new_filter i:hover {
  cursor: pointer;
}
</style>
<style lang="scss">
.nextticketFilter {
  width: 400px !important;
  .el-select-dropdown__item {
  white-space: break-spaces !important;
}
}
.nextTicket_filterText {
  width: 400px !important;

  .el-select-dropdown__item {
  white-space: break-spaces !important;
}
}
</style>
